package cn.growthgate.fgo.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;

import cn.growthgate.fgo.common.base.BaseServiceImpl;
import cn.growthgate.fgo.entity.MyServantBond;
import cn.growthgate.fgo.mapper.MyServantBondMapper;
import cn.growthgate.fgo.service.IMyServantBondService;
import cn.growthgate.fgo.util.DateUtils;

/**
 * <p>
 * 我的从者羁绊 服务实现类
 * </p>
 *
 * @author GrowthGate
 * @since 2019-05-29
 */
@Service
public class MyServantBondServiceImpl extends BaseServiceImpl<MyServantBondMapper, MyServantBond>
		implements IMyServantBondService {

	@Override
	public boolean deleteByMyServantIds(List<Long> myServantIds) {
		return delete(newWrapper().in("myServantId", myServantIds));
	}

	@Override
	public Integer getDailyBond(Long myServantId) {
		List<MyServantBond> list = selectList(
				newWrapper().eq("myServantId", myServantId).orderBy("date", false).last("LIMIT 2"));
		if (list.size() == 2) {
			MyServantBond lastBond = list.get(0);
			MyServantBond lastButOneBond = list.get(1);
			int diffValue = lastBond.getValue() - lastButOneBond.getValue();
			int diffDay = DateUtils.getDiffDay(lastButOneBond.getDate(), lastBond.getDate());
			if (diffDay > 0 && diffValue >= 0) {
				return diffValue / diffDay;
			}
		}
		return null;
	}

	@Override
	public boolean insertOrUpdateByDate(Long myServantId, Date date, Integer level, Integer value) {
		MyServantBond servantBond = selectOne(newWrapper().eq("myServantId", myServantId).eq("date", date));
		if (servantBond == null) {
			servantBond = new MyServantBond();
			servantBond.setMyServantId(myServantId);
			servantBond.setDate(date);
		}
		servantBond.setLevel(level);
		servantBond.setValue(value);
		return insertOrUpdate(servantBond);
	}

}
